package org.particles.domain;

import java.util.LinkedList;
import java.util.List;

/**
 * contains statistic to a simulation parameter. it holds
 * history to average, min, max values of the parameter.
 */
public class Statistic {
	/** name of simulation parameter. */
	private String name;
	private LinkedList<StatisticItem> statisticItems = new LinkedList<StatisticItem>();
	private int historySize = 300;
	
	public Statistic(final int historySize) {
		this.historySize = historySize;
	}
	
	public Statistic() {
	}
	
	/** @param name of simulation parameter. */
	public Statistic(final String name) {
		this.name = name;
	}
	
	/** @return name of simulation parameter. */
	public String getName() {
		return name;
	}
	
	/** @param name of simulation parameter. */
	public void setName(final String name) {
		this.name = name;
	}
	
	public int getHistorySize() {
		return historySize;
	}

	public void addStatisticItem(final StatisticItem item) {
		if(statisticItems.size() > historySize) {
			// shift values in the list
			statisticItems.removeFirst();
			statisticItems.addLast(item);
		}
		else {
			statisticItems.add(item);
		}
	}
	
	public void clearStatistic() {
		statisticItems.clear();
	}
	
	/**
	 * 
	 * @param statType one of values 
	 * StatisticItem.STAT_AVG | StatisticItem.STAT_MIN | StatisticItem.STAT_MAX.
	 * @param statValues into which statistical values should be written.
	 * the size should be of "Statistic.historySize". if not nothing is written
	 * into list. if statistic has no elements, statValues will be cleared.
	 */
	public void writeStatistic(final int statType, final List<Double> statValues) {
		if(statValues == null || (StatisticItem.STAT_AVG != statType
				&& StatisticItem.STAT_MIN != statType
				&& StatisticItem.STAT_MAX != statType)) {
			return;
		}
		if(statisticItems.size() < 1) {
			statValues.clear();
			return;
		}
		int i = 0;
		for(final StatisticItem statisticItem : statisticItems) {
			if(StatisticItem.STAT_AVG == statType) {
				setOrAddStatValue(statValues, i, statisticItem.getAverage());
			}
			else if(StatisticItem.STAT_MIN == statType) {
				setOrAddStatValue(statValues, i, statisticItem.getMin());
			}
			else if(StatisticItem.STAT_MAX == statType) {
				setOrAddStatValue(statValues, i, statisticItem.getMax());
			}
			i++;
		}
	}
	
	private void setOrAddStatValue(final List<Double> statValues, final int index, final double value) {
		if(statValues.size() - 1 < index) {
			statValues.add(value);
		}
		else {
			statValues.set(index, value);
		}
	}
}
